<template>
	<view :class="'wrapper ' + (bg ? '' : 'none')" v-if="show">
		<view class="content">
			<view class="avatar">
				<!-- #ifdef MP-WEIXIN -->
				<open-data class="img" type="userAvatarUrl"></open-data>
				<!-- #endif -->
				
			</view>
			<view class="desc">
				<lang keywords="为了您更方便的使用我们的小程序,我们需要获取您的公开信息（昵称、头像等）"></lang>
			</view>
			<view class="btn-wrapper">
				<!-- #ifdef MP-WEIXIN -->
				<button type="primary" open-type="getUserInfo" @getuserinfo="clickScope" lang="zh_CN">
					<lang keywords="点击授权"></lang>
				</button>
				<!-- #endif -->
				
				<!-- #ifdef MP-ALIPAY -->
				<button type="primary" open-type="getAuthorize"  @tap="clickScope" scope='userInfo'>
					<lang keywords="点击授权"></lang>
				</button>
				<!-- #endif -->
			</view>
			<text class="iconcha" v-if="showCancel" @click.stop="close">×</text>
		</view>
	</view>
</template>

<script>
	import common from '../../utils/common.js';

	var _this;
	var app = getApp();
	export default {
		name: 'userinfo',
		props: {
			options: {
				type: Object,
				default: {}
			},
		},
		data() {
			return {
				toLogin: false,
				// 检查是否有权限可以直接登录
				show: false,
				// 是否显示授权弹窗 true显示  false不显示
				showCancel: true,
				// 授权弹窗是否显示关闭按钮 true显示 false不显示
				bg: true,
				// 授权弹窗背景是否透明 true背景透明 false背景不透明
				content: '',
				// 点击关闭之后弹窗内容
				url: '',
				// 关闭之后是否跳转
				goType: 'relanch',
				// url跳转类型 默认relanch
				refuseIsShow: false,
				// 拒绝授权后是否继续显示弹窗  true显示 false不显示
				codeLogin: false, 
				// 是否只使用codeLogin登录
				showWebMask: false,
				// h5跳转登录前是否弹窗提示
				webLoginTip: '您还未登录，请先登录进行操作。',
				// h5跳转登录前弹窗提示内容
				third_id: '',
				isGetScope: false
			}
		},
		watch: {
			options: {
				immediate: true,
				handler(val) {
					let _this = this
					let options = val
					console.log('67 userInfo', options)
					if (JSON.stringify(options) == '{}') {
						_this.show = false
					}

					if (options.toLogin && options.toLogin == true) {
						// #ifdef H5
						if (!options.codeLogin) {
							if (options.showWebMask) {
								uni.showModal({
									title: common.changeTxt('提示'),
									content: options.webLoginTip ? options.webLoginTip : common.changeTxt(_this.webLoginTip),
									showCancel: options.showCancel,
									cancelText: common.changeTxt('先看看'),
									confirmText: common.changeTxt('去登录'),
									cancelColor: '#999999',
									success: (res) => {
										if (res.confirm) {
											_this.webToLogin()
										} else {
											_this.$emit('toLogin', {});
										}
									},
									fail: () => {
										_this.$emit('toLogin', {});
									}
								})
							} else {
								_this.webToLogin()
							}
						}
						// #endif
						
						// #ifdef MP-WEIXIN || MP-ALIPAY
						for (var i in options) {
							this[i] = options[i]
						}
						this.codeLoginFunc().then(res => {
							app.globalData.is_login = true;

							_this.$emit('toLogin', {
								userInfo: res.user
							});
						}, res => {
							app.globalData.is_login = false;

							_this.show = !this.codeLogin

							_this.$emit('toLogin', {});
						});
						
						
						// #endif
					}
				}
			}
		},
		created() {
			_this = this;
		},
		methods: {
			webToLogin () { 
				console.log('userinfo webToLogin')
				var tmpDomain = common.requestDomain;
				if (tmpDomain == '/') {
					tmpDomain = 'http://www.group.com/';
				}
				var url = tmpDomain + 'packapp/my/login.html?back=' + encodeURIComponent(location.href) + '&loginFail=' +
					encodeURIComponent(location.href)
				location.replace(url)
			},
			goUrl(url) {
				var goType = _this.goType;

				if (goType == 'relanch') {
					wx.reLaunch({
						url: url
					});
				} else if (goType == 'navigate') {
					wx.navigateTo({
						url: url
					});
				} else if (goType == 'tab') {
					wx.switchTab({
						url: url
					});
				} else if (goType == 'back') {
					wx.navigateBack({
						delta: -1
					});
				} else {
					common.parseUrl(url);
				}
			},
			
			clickScope(e) {
				let _this = this;
				// #ifdef MP-ALIPAY
				console.log('1111111111222', e)
				app.globalData.getAlipayScope = true
				let timer = setInterval(function(){
					if (!app.globalData.getAlipayScope || _this.isGetScope) {
						app.globalData.getAlipayScope = false
						clearInterval(timer) 
						_this.getAliUserinfo()
					}
				}, 500)
				// #endif
				
				// #ifdef MP-WEIXIN
				if (e.detail.errMsg == 'getUserInfo:fail auth deny') {
					app.globalData.is_login = false;

					if (_this.content != '') {
						wx.showModal({
							title: common.changeTxt('提示'),
							content: _this.content,
							showCancel: false,
							success: res => {
								if (res.confirm && _this.url != '') {
									_this.goUrl(_this.url);
								}
							}
						});
					} else if (_this.url != '') {
						_this.goUrl(_this.url);
					}

					this.$emit('getUserscope', {});

					_this.show = _this.refuseIsShow;
				} else {
					var result = {
						iv: e.detail.iv,
						encryptedData: e.detail.encryptedData
					};
					_this.loginApi(result)
				}
				// #endif
			},

			close() {
				this.show = false;

				if (this.url) {
					this.goUrl(this.url);
				}

				this.$emit('getUserscope', {});
			},

			codeLoginFunc() {
				return new Promise(function(resolve, reject) {
					//调用登录接口
					var ticket = uni.getStorageSync('ticket');

					if (!ticket) {
						
						uni.login({
							success: res => {
								
								uni.setStorageSync('code', res.code);

								// #ifdef  MP-WEIXIN
								var post_url = "Wxapp&a=code_login";
								var postData = {
									code: res.code
								}
								// #endif

								// #ifdef  MP-ALIPAY
								var post_url = "Wxapp&a=alipayapp_login"
								var postData = {
									auth_code: res.code
								}
								// #endif

								common.post(post_url, postData, data => {
									// #ifdef MP-ALIPAY
									if (data.third_id) {
										_this.third_id = data.third_id
										if (!_this.codeLogin) {
											_this.getAliUserinfo('first')
										} else {
											reject({})
										}
									} else if (data.user.nickname == '支付宝用户') {
										console.log('支付宝用户授权登录')
										uni.setStorageSync('ticket', data.ticket);
										_this.getAliUserinfo('first')
									} else {
										_this.getUserInfoSuccess(data);
										resolve(data);
									}
									// #endif
									
									// #ifdef MP-WEIXIN
									if (data.emptyUser == true) {
										console.log('wxapp - getUserInfo');
										uni.getUserInfo({
											withCredentials: true,
											lang: 'zh_CN',
											success: (result) => {
												_this.loginApi(result)
											},
											fail: res => {
												if (!_this.codeLogin) {
													_this.show = true
												} else {
													reject(res);
												}
											}
										});
									} else {
										_this.getUserInfoSuccess(data);
										resolve(data);
									}
									// #endif
								});
							},
							fail: res => {
								reject(res);
							}
						});
					} else {
						common.post('Wxapp&a=login', {
							ticket: ticket
						}, function(data) {
							
							_this.getUserInfoSuccess(data);

							resolve(data);
						});
					}
				});
			},
			
			getAliUserinfo (tag) {
				var _this = this
				my.getAuthCode({
				  scopes: 'auth_base',
				  success: (resCode) => {
					my.getOpenUserInfo({
						fail: (res) => {
							console.log('支付宝获取用户信息失败', res)
						},
						success: (res) => {
					        let resData = JSON.parse(res.response).response // 以下方的报文格式解析两层 response
							console.log('支付宝获取用户信息成功', resData)
							if (resData.msg == 'Success' && resData.code == '10000') {
								_this.show = false
								let param = {
									nickName: resData.nickName,
									avatar: resData.avatar,
									province: resData.province,
									city: resData.city,
									gender: resData.gender,
									auth_code: resCode.authCode
								} 
								common.post('Wxapp&a=alipayapp_login', param, function(data){
									console.log('支付宝授权用户信息',  data)
									if (data.third_id) {
										if (!_this.isGetScope) {
											uni.$once('loginSuccess', function(data){
												console.log('监听到事件来自 loginSuccess ，携带参数 msg 为：', data);
												if (data.user) {
													_this.show = false
													_this.getUserInfoSuccess(data)
													_this.$emit('getUserscope', {
														userInfo: data.user
													});
												}
											})
										}
										_this.isGetScope = true
										_this.show = true
										uni.navigateTo({
											url: '/pages/my/newnumber?third_id=' + data.third_id + '&third_from=' + data.third_from
										})
										return
									}
									_this.getUserInfoSuccess(data)
									_this.$emit('getUserscope', {
										userInfo: data.user
									});
								})
							} else {
								uni.removeStorageSync('ticket');
								if (tag && tag == 'first' && !_this.codeLogin) {
									console.log('登录失败11155555', _this.show)
									_this.$nextTick(function(){
										_this.show = true
										console.log('登录失败111', _this.show)
									})
								} else {
									_this.show = _this.refuseIsShow
									console.log('登录失败222', _this.show)
									if (!_this.show) {
										_this.$emit('getUserscope', {});
									}
								}
							}
						}
					});
				  },
				});
				
			},

			loginApi: function(result) {
				wx.login({
					success: res => {
						common.post('Wxapp&a=wxapp_login', {
							code: res.code,
							encryptedData: result.encryptedData,
							iv: result.iv
						}, data => {
							if (data.third_id) {
								if (!_this.isGetScope) {
									uni.$once('loginSuccess', function(data){
										console.log('监听到事件来自 loginSuccess ，携带参数 msg 为：', data);
										if (data.user) {
											_this.show = false
											_this.getUserInfoSuccess(data)
											
											_this.$emit('getUserscope', {
												userInfo: data.user
											}); 
											
										}
									})
								}
								_this.isGetScope = true
								_this.show = true
								uni.navigateTo({
									url: '/pages/my/newnumber?third_id=' + data.third_id + '&third_from=' + data.third_from
								})
							} else if (data.user) {
								_this.getUserInfoSuccess(data);
								_this.$emit('getUserscope', {
									userInfo: data.user
								});
							}
						});
					},
					fail: res => {
						console.log('小程序登录错误', res); // 标记wx.login()失败
						if (!_this.codeLogin && !_this.show && _this.refuseIsShow) {
							_this.show = true
						} else {
							_this.$emit('getUserscope', {});
						}
					}
				});
			},

			getUserInfoSuccess(result) {
				console.log('6666666666678978', result);

				if (!result.user) {
					wx.removeStorageSync('ticket');
					this.codeLoginFunc().then(res => {
						console.log('7777777666678978', result);
						
						app.globalData.is_login = true;

						_this.$emit('toLogin', {
							userInfo: res.user
						});
					}, res => {
						app.globalData.is_login = false;

						_this.show = !this.codeLogin;

						_this.$emit('toLogin', {});
					});
					return;
				}

				uni.setStorageSync('ticket', result.ticket);
				uni.setStorageSync('openId', result.user.openid);
				uni.setStorageSync('alipayUid', result.user.alipay_uid);

				if (result.user.phone) {
					uni.setStorageSync('isPlatUser', '1');
				} else {
					uni.setStorageSync('isPlatUser', '0');
					result.user.phone = '';
				}

				app.globalData.userInfo = result.user;
				app.globalData.is_login = true
				uni.setStorageSync('auto_door_open', result.user.auto_door_open);
			}
		}
	}
</script>
<style scoped>
	.wrapper {
		width: 100%;
		height: 100%;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, .7);
		z-index: 999999;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.wrapper.none {
		background: #eee;
	}

	.content {
		width: 75%;
		background: #fff;
		text-align: center;
		padding: 60rpx;
		box-sizing: border-box;
		font-size: 16px;
		border-radius: 10rpx;
		max-width: 400px;
		position: relative;
	}

	.avatar {
		width: 40%;
		padding-top: 40%;
		border-radius: 50%;
		overflow: hidden;
		margin: 0 auto 40rpx;
		position: relative;
	}

	.avatar .img {
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
		left: 0;
	}

	.desc {
		line-height: 1.4;
		color: #888;
		margin-bottom: 40rpx;
	}

	.iconcha {
		position: absolute;
		right: 0;
		top: 0;
		font-size: 28px;
		color: #888;
		padding: 0 10px;
	}
</style>
